import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import * as api from "../api/cabinet"
import stringRandom from 'string-random';

export const useCabinetStore = defineStore('cabinet', {
  state: ()=>({
    data: []
  }),
  getters: {
    // 移除指定机柜
    remoteCabinetStore: (id) => {

    }, 
  },
  actions: {
    // 增加机柜
    async addCabinet(name) {
      // 请求后端数据
      name = name?name: ""
      if(name === "") {
        alert("请命名机柜")
        return
      }
      let newCab = {name, code: stringRandom(16), count: 0}
      let res = await api.addCabinet(newCab)
      // 添加前端数据
      if(res) {
        newCab.id = res.id  // 赋值数据库生成的id
        this.data.push(newCab)
      }

    },
    async updateCabinet(_data) {
     
      let data = {
        id: _data.id,
        name: _data.name,
        code: _data.code,
      }
      let res = await api.updateCabinet(data) 
      // 成功后返回并调用结果
      if(res) {
        this.data = this.data.map((item) => {
          if(item.code == data.code) { 
            item.name = data.name
          }
          return item
        })
      }

    },
    // 返回执行结果，用于取消选中。
    async deleteCabine(index){
      console.log(this.data[index])
      let res = await api.deleteCabinet(this.data[index].id)
      if(res){
        this.data.splice(index, 1)
        return true
      }
      return false
    },

    // 增加服务器
    async addServer(_data) {
     
      let data = {
        id: _data.id,
        name: _data.name,
        code: _data.code,
        count: _data.count +1
      }
      let res = await api.updateCabinet(data) 
      // 成功后返回并调用结果 
      if(res) { 
        this.data = this.data.map((item) => {
          if(item.code == data.code) { 
            item.name = data.name 
            item.count = data.count
          }
          return item
        })
      }

    }

  }
})


